package com.alipay.app.groupmeal.standard.ui.c.abcp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

import com.alibaba.fastjson.JSONObject;
import com.alipay.app.groupmeal.standard.R;
import com.alipay.app.groupmeal.standard.base.BaseMVCActivity;
import com.alipay.app.groupmeal.standard.constant.BaseConstant;
import com.alipay.app.groupmeal.standard.event.EventManager;
import com.alipay.app.groupmeal.standard.ui.MainActivity;
import com.alipay.app.groupmeal.standard.ui.b.function.result.BScreenResult;
import com.alipay.app.groupmeal.standard.ui.b.function.result.ResultPre;
import com.alipay.iot.bpaas.api.service.BPaaSCallback;
import com.alipay.iot.bpaas.api.service.BPaaSResponse;
import com.alipay.sdk.abcphaima.AbcpHM;
import com.alipay.sdk.abcphaima.AbcpHMResultPage;
import com.alipay.sdk.abcphaima.bean.AbcpPageResultData;
import com.alipay.sdk.abcphaima.bean.PageResultData;
import com.alipay.sdk.util.LogUtil;
import com.alipay.sdk.util.TextUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Action;
import io.reactivex.rxjava3.functions.Consumer;

/**
 * @ProjectName: 团餐
 * @ClassName: CPayResultAbcpActivity
 * @Description: C屏组件支付结果页, 主要负责控制B屏UI
 * @Author: bd-001935
 * @CreateDate: 5/18/22 2:14 PM
 * @UpdateUser: bd-001935
 * @UpdateDate: 5/18/22 2:14 PM
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class CPayResultAbcpActivity2 extends BaseMVCActivity {

    private ResultPre resultPre;
    Disposable mDisposable;

    private boolean isSuccess;

    private String amount;
    private List<BScreenResult.ResultBean> bList;

    private int isFailType = BaseConstant.FAIL_TYPE.PAY;
    private String failMsg;
    //倒计时
    private int count;
    private PageResultData mResultData;

    /**
     * @param activity
     */
    public static void startAct(Activity activity, PageResultData pageResultData) {
        Intent intent = new Intent(activity, CPayResultAbcpActivity2.class);
        intent.putExtra("resultBean", pageResultData);
        activity.startActivity(intent);
        if (activity != null && !(activity instanceof MainActivity))
            activity.finish();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_transparent;
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        mResultData = (PageResultData) intent.getSerializableExtra("resultBean");
        showResultPage();
        mDisposable = Flowable.intervalRange(0, count, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        resultPre.setResultPageIntervalTime((count - aLong) + "秒");
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        onBackClick();
                    }
                })
                .subscribe();

    }

    @Override
    public void initPresentation() {
        super.initPresentation();
        if (mDisplay != null) {
            resultPre = new ResultPre(this, mDisplay);
            registerPresentation(resultPre);
            resultPre.setKeyEventListener(new ResultPre.ResultPreKeyEventListener() {
                @Override
                public void onEnterKey(boolean isSuccess, int isFailType) {
                    if (isSuccess) {
                        onBackClick();
                    } else {
                        if (isFailType == BaseConstant.FAIL_TYPE.PAY) {
                            //支付失败,不清空金额
                            onBackClick();
                        }
                    }
                }
            });
            showPresentation(resultPre);
            if (isSuccess) {
                resultPre.showPaySuccessPageResult(amount, bList);
            } else {
                if (isFailType == BaseConstant.FAIL_TYPE.PAY) {
                    resultPre.showFailPageResult(failMsg, isFailType);
                } else
                    resultPre.showUnknownPageResult(failMsg);
            }
        }
    }

    @Override
    protected void dissmissPresnetation() {
        if (resultPre != null) {
            resultPre.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();

        }
        mDisposable = null;
        super.onDestroy();
    }

    private void onBackClick() {
        if (isSuccess)
            EventBus.getDefault().post(new EventManager.clearAmount());
        if (mResultData != null)
            AbcpHMResultPage.closePayResult(mResultData.sessionId);
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        onBackClick();
    }

    @Override
    public boolean onKeyEventEnter(KeyEvent event) {
        if (resultPre != null && resultPre.isShowing())
            return resultPre.dispatchKeyEvent(event);
        return super.onKeyEventEnter(event);
    }

    private void showResultPage() {
        if (mResultData == null) {
            return;
        }
        AbcpPageResultData data = new AbcpPageResultData(mResultData);
        data.sessionId = mResultData.sessionId;
        data.tradeNo = mResultData.tradeNo;
        data.authCode = mResultData.authCode;
        data.paidAmount = mResultData.paidAmount;
        data.discountAmount = mResultData.discountAmount;
        data.totalAmount = mResultData.totalAmount;

        isSuccess = mResultData.success;
        failMsg = mResultData.message;
        amount = mResultData.totalAmount;

        if (mResultData.success) {
            data.success = true;
            data.title = "支付成功";
            bList = new ArrayList<>();
            bList.add(new BScreenResult.ResultBean("合计", "¥" + mResultData.totalAmount));
            if (!TextUtil.isEmpty(mResultData.buyerLogonId))
                bList.add(new BScreenResult.ResultBean("支付宝账号", mResultData.buyerLogonId));
            if (mResultData.type == 2) {
//                data.resultTimeOut = 3;
            }
            count = data.resultTimeOut;
        } else {
            data.title = "支付失败";
            data.subCode = mResultData.failCode;
            data.subMsg = mResultData.message;
            count = 3;
        }

        AbcpHMResultPage.showPayResult(data, mResultData.type);
    }


}
